$(function () {
    var num = 3;    // 提前天数
    var startTime = (new Date).getTime() - num * 24 * 60 * 60 * 1000;
    $("#followUpTime").datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        startDate: new Date(startTime).Format("yyyy-MM-dd"),
        endDate: new Date(),
    });
    $('#followUpTime').val(new Date().Format("yyyy-MM-dd"))
    $("#nextFollowTime").datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        startDate: new Date()
    });
    initScore();
    uploadImg();
    getFollowWay();
    initTag();
    $("#nameBox").css('display', 'none');

    $('select').selectpicker({
        sanitize: true,
        size: 10
    });

    getCustomerSelect()




    $('.card-body').bootstrapValidator({
        fields: {
            customerInput: {
                validators: {
                    notEmpty: {
                        message: '客户名称不能为空'
                    }
                }
            },
            followUpTime: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '跟进日期不能为空'
                    }
                }
                // validators: {
                //     notEmpty: {
                //         message: '跟进日期不能为空'
                //     },
                //     // stringLength: {
                //     //     max: 40,
                //     //     message: '客户名称长度不能大于40个字符！'
                //     // }
                // }
            },
            // nextFollowTime: {
            //     trigger:"change",
            //     validators: {
            //         notEmpty: {
            //             message: '下次跟进时间不能为空'
            //         }
            //     }
            // },
            name: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '联系人姓名不能为空'
                    }
                },
            },
            phone: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '手机号不能为空'
                    },
                    // regexp: {
                    //     regexp: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                    //     message: '请输入正确的手机号'
                    // }
                    stringLength:{
                        max:12,
                        message: '请输入正确的手机号'
                    }
                }
            },
            email: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '联系人姓名不能为空'
                    }
                }
            },
            address: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '客户地址不能为空'
                    }
                }
            },
            // customerIntention: {
            //     trigger:"change",
            //     validators: {
            //         notEmpty: {
            //             message: '客户意向不能为空'
            //         }
            //     }
            // },
            // customerQuality: {
            //     validators: {
            //         notEmpty: {
            //             message: '客户质量不能为空'
            //         }
            //     }
            // },
            followPurpose: {
                validators: {
                    notEmpty: {
                        message: '跟进目的不能为空'
                    }
                }
            },
            wayItem: {
                validators: {
                    notEmpty: {
                        message: '请选择二级跟进目的'
                    }
                }
            },
            communicationTime: {
                validators: {
                    notEmpty: {
                        message: '沟通时长不能为空'
                    }
                }
            },
            followDetail: {
                validators: {
                    notEmpty: {
                        message: '跟进详情不能为空'
                    }
                }
            },
            accompanyingPerson:{
                validators: {
                    notEmpty: {
                        message: '陪访人不能为空'
                    }
                }
            },
            wechat:{
                validators: {
                    notEmpty: {
                        message: '微信号不能为空'
                    }
                }
            },
            mainVisitor:{
                validators: {
                    notEmpty: {
                        message: '主拜访人不能为空'
                    }
                }
            },
            address:{
                validators: {
                    notEmpty: {
                        message: '地址不能为空'
                    }
                }
            }
        }
    });
    $('.tagsinput').tagsinput({
        maxChars : 5
    });
    $('.bootstrap-tagsinput input').attr('maxlength',5)



});


$(document).keypress(
function(event){
    if (event.which == '13') {
        event.preventDefault();
    }
});

// 标签
function initTag() {
    $("#tagBox").html('');
    $("#tagBox").append('<input type="text" name="staticPath" value="" id="staticPath2"/>');
    $("#staticPath2").val('');
    WS({
        el: "#staticPath2",
    });
}

// 获取跟进方式
function getFollowWay() {
    var type = $("#type").val();
    var followUpMode = '';
    if (type == 1) {
        followUpMode = "线上跟进"
    } else if (type == 2) {
        followUpMode = "拜访"
    } else if (type == 3) {
        followUpMode = "微信"
    } else if (type == 4) {
        followUpMode = "线下电话"
    } else if (type == 5) {
        followUpMode = "邮箱"
    } else if (type == 6) {
        followUpMode = "陪访"
    }
    $("#followUpMode").val(followUpMode)
    $('h1').html(followUpMode)
}

// 评分插件
function initScore() {
    jQuery.fn.raty.defaults.hints = ["超烂", "差", "一般", "好", "很好"],
        jQuery(".js-raty").each(function () {
            var a = jQuery(this);
            a.raty({
                starType: "i",
                targetText: a.data("target-text") ? a.data("target-text") : '',
                score: a.data("score") ? a.data("score") : 0,
                number: a.data("number") ? a.data("number") : 5,
                cancel: a.data("cancel") ? a.data("cancel") : !1,
                target: a.data("target") ? a.data("target") : !1,
                targetScore: a.data("target-score") ? a.data("target-score") : !1,
                precision: a.data("precision") ? a.data("precision") : !1,
                cancelOff: a.data("cancel-off") ? a.data("cancel-off") : "mdi mdi-close fa-1-5x text-danger",
                cancelOn: a.data("cancel-on") ? a.data("cancel-on") : "mdi mdi-close fa-1-5x",
                starHalf: a.data("star-half") ? a.data("star-half") : "mdi mdi-star-half fa-1-5x text-warning",
                starOff: a.data("star-off") ? a.data("star-off") : "mdi mdi-star fa-1-5x text-gray",
                starOn: a.data("star-on") ? a.data("star-on") : "mdi mdi-star fa-1-5x text-warning",
                click: function (score, e) {
                }
            })
        })
}

// 跟进目的的切换
function followWay(obj) {
    $("#wayItem").attr('disabled', false);
    if ($(obj).val() == 1) {
        $("#wayItem").html('<option value="1">会员产品</option>\n' +
            '<option value="2">非会员产品</option>')
    } else {
        $("#wayItem").html('<option value="1">询问意向</option>\n' +
            '<option value="2">再次跟进</option>\n' +
            '<option value="3">成交</option>\n' +
            '<option value="4">意向关怀</option>')
    }
    $("#wayItem").selectpicker('refresh');
    if($('.bv-form').data('bootstrapValidator')!=undefined){
        $('.bv-form').data('bootstrapValidator')
            .updateStatus('wayItem', 'NOT_VALIDATED', null)
            .validateField('wayItem');
    }
}

// 上传图片
function uploadImg() {
    $(document).on('click', '.file-browser', function () {
        var file = $(this).closest('.file-group').find('[type="file"]');
        file.on('click', function (e) {
            e.stopPropagation();
        });
        file.trigger('click');
    });

    $(document).on('change', '.file-group [type="file"]', function () {
        var $this = $(this);
        var $imgDiv = $(this).closest('.file-group').find('.img-box');
        var $imageId = $(this).closest('.file-group').find('.image-id');
        var $input = $(this)[0];
        var $len = $input.files.length;
        var formFile = new FormData();
        if ($len == 0) {
            return false;
        } else {
            var fileAccaccept = $this.attr('accaccept');
            var fileType = $input.files[0].type;
            var type = (fileType.substr(fileType.lastIndexOf("/") + 1)).toLowerCase();

            if (!type || fileAccaccept.indexOf(type) == -1) {
                lightyear.notify('您上传图片的类型不符合(.jpg|.jpeg|.gif|.png|.bmp)', 'danger', 1000);
                return false;
            }
            formFile.append("file", $input.files[0]);
        }
        var data = formFile;
        $.ajax({
            url: '/file/uploadByOneFile',
            data: data,
            type: "POST",
            dataType: "json",
            cache: false,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.code == "000000") {
                    $imgDiv.html('<img src="' + data.data.accessUrl + '">')
                    $imageId.val(data.data.fileId);
                }
            },
            error: (function (res) {
                $.alert("失败");
            })
        });
    });
}


// 获取联系人
function changeName(_this) {
    var $this = _this;
    //联系人姓名
    var name = $.trim($("#name").val());
    //从哪跳转到跟进页面（0：线索；1：客户）
    var source = $("#source").val();
    //线索/客户id
    var id = $("#customerInput").val();
    var status;
    if (!name) {
        status = '0';
    } else {
        status = '1';
    }
    $.ajax({
        url: '/clueContact/clueContact/echo',
        data: {
            name: name,
            status: status,
            id: id,
            source: source
        },
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        success: function (data) {
            if (data.code == '000000') {
                $("#nameBox").css("display", 'block');
                $("#nameBox").html('');
                if (data.data.length <= 0) {//把页面上之前赋值的联系人id置空
                } else {
                    let str = '';
                    for (let i = 0; i < data.data.length; i++) {
                        str += '<li><a href="javascript:void(0);" class="name-item" onclick="getTel(\'' + data.data[i].contactName + '\',\'' + data.data[i].contactInformation + '\')">' + data.data[i].contactName + '</a></li>'
                    }
                    $("#nameBox").html(str);
                }
            }
        }
    });

    // 点击输入框和下拉菜单以外范围，关闭提示下拉菜单
    $(document).click(function (e) {
        var con = $($this).parents('.form-content');
        if (!con.is(e.target) && con.has(e.target).length === 0) {
            $("#nameBox").slideUp(160);
        }
    })
}

//
function getTel(name, phone) {
    $("#name").val(name);
    $("#phone").val(phone);
    $('#phone').change()
    $('#name').change()
    var customerType = $('#customerInput option:selected').data('type');
    $('#phone').attr('disabled', true);
    $("#extNumber").attr('disabled',true)
    if(customerType == '1') {
        $('#name').attr('disabled', true);
        $('#phone').attr('disabled', true);
    }
    $("#nameBox").css("display", 'none');
}


/**
 * 添加线索跟进
 */
function addClueFollow() {
    //线索id
    var clueId;
    //客户id
    var customerId;
    //附件（拜访(2) 陪访(6) 微信(3) 邮箱(5)）
    var attachmentUploadId;

    //线索池id
    var poolId = $.trim($("#poolId").val());

    //从哪跳转到跟进页面（0：线索；1：客户）
    var source = $("#source").val();
    if (source == "0") {
        clueId = $.trim($("#customerInput").val());
    } else if (source == "1") {
        customerId = $.trim($("#customerInput").val());
    }

    //跟进方式：1-线上电话；2-拜访 3-微信 4-线下电话 5-邮箱 6-陪访
    var followWay = $.trim($("#type").val());

    //跟进时间
    var followTm = $.trim($("#followUpTime").val());

    //下次跟进时间
    var nextPlanTime = $.trim($("#nextFollowTime").val());

    //线索联系人表id 空(手动输入的联系人姓名 联系方式) 非空(选择现有的线索联系人信息)
    var clueContactId = $.trim($("#clueContactId").val());

    //联系人姓名
    var contactName = $.trim($("#name").val());

    //联系人电话
    // var contactInformation = $.trim($("#phone").val());
    if($('#extNumber').val() == ''){
        var contactInformation = $.trim($("#phone").val());
    }else{
        var contactInformation = $.trim($("#phone").val()+' - '+$('#extNumber').val());
        console.log(contactInformation)
    }

    //联系人邮箱
    var email = $.trim($("#email").val());

    //拜访地址
    var visitAddress = $.trim($("#address").val());

    //客户意向(百分比)
    var customerIntention = $.trim($("#customerIntention").val());

    //客户质量:1-优；2:良；3:一般
    var customerQuality = $.trim($("#customerQuality").val());

    //跟进目的：1-跟进产品；2-过程管理
    var followPurpose = $("#followPurpose").find("option:selected").val();

    //跟进目的 当followPurpose=1 (产品类别 1会员 2非会员) 当followPurpose=2(过程类别 1询问意向 2再次跟进 3成交 4意向关怀)
    var followValue = $("#wayItem").find("option:selected").val();

    //沟通时长(分)，线上电话(1)沟通时长是秒
    var communicationTime = $.trim($("#communicationTime").val());

    //陪访人
    var accompanyingPerson = $.trim($("#accompanyingPerson").val());

    //主拜访人
    var mainVisitor = $.trim($("#mainVisitor").val());

    //微信号
    var wechat = $.trim($("#wechat").val());

    //线索评分（0-10分）
    var clueScore = $.trim($('#clueScore').raty('score'));

    //线索标签tag
    var tagStr = $('.tagsinput').val().split(' ').join(',');
    // var tagStrNew = tagStr.substring(0, tagStr.lastIndexOf(',')) + tagStr.substring(tagStr.lastIndexOf(',') + 1);
    var tag = tagStr;

    //跟进详情
    var followDetail = $.trim($("#followDetail").val());

    //帮助说明
    //var remark = $.trim($("#remark").val());

    //上传电话账号页
    var accountUploadId = $.trim($("#telScreen").val());

    //上传电话时长页
    var minUploadId = $.trim($("#timeScreen").val());

    var customerType = $('#customerInput option:selected').data('type');

    // if (!customerId) {
    //     promptInfo("请选择跟进客户!");
    //     return;
    // }
    // if (!followTm) {
    //     promptInfo("跟进时间不能为空!");
    //     return;
    // }
    //
    // if (!nextPlanTime) {
    //     promptInfo("下次跟进时间不能为空!");
    //     return;
    // }
    //
    // if (followWay != '5') {
    //     if (!contactName) {
    //         promptInfo("联系人姓名不能为空!");
    //         return;
    //     } else if (contactName.length > 40) {
    //         promptInfo("联系人姓名不能大于40个字！");
    //         return;
    //     }
    //
    //     if (!contactInformation) {
    //         promptInfo("联系人电话不能为空!");
    //         return;
    //     } else if (contactInformation.length > 20) {
    //         promptInfo("联系人电话不能大于20个数字！");
    //         return;
    //     }
    // }
    //
    // if (followWay == '5') {
    //     if (!email) {
    //         promptInfo("邮箱不能为空!");
    //         return;
    //     } else if (email.length > 25) {
    //         promptInfo("邮箱不能大于25个字！");
    //         return;
    //     }
    // }
    //
    // if (!customerIntention) {
    //     promptInfo("客户意向不能为空!");
    //     return;
    // } else if (customerIntention.length > 255) {
    //     promptInfo("客户意向不能大于255个数字！");
    //     return;
    // }
    //
    // if (!customerQuality) {
    //     promptInfo("客户质量不能为空!");
    //     return;
    // }
    //
    // if (!followPurpose) {
    //     promptInfo("跟进目的不能为空!");
    //     return;
    // }
    // if (!followValue) {
    //     promptInfo("跟进目的类型不能为空!");
    //     return;
    // }
    //
    // if (followWay == '2' || followWay == '6') {
    //     if (!visitAddress) {
    //         promptInfo("地址不能为空!");
    //         return;
    //     } else if (visitAddress.length > 255) {
    //         promptInfo("地址不能大于255个字！");
    //         return;
    //     }
    // }
    //
    // if (followWay == '2') {
    //     if (!accompanyingPerson) {
    //         promptInfo("陪访人不能为空!");
    //         return;
    //     } else if (accompanyingPerson.length > 40) {
    //         promptInfo("陪访人不能大于40个字！");
    //         return;
    //     }
    // }
    //
    // if (followWay == '6') {
    //     if (!mainVisitor) {
    //         promptInfo("主拜访人不能为空!");
    //         return;
    //     } else if (mainVisitor.length > 40) {
    //         promptInfo("主拜访人不能大于40个字！");
    //         return;
    //     }
    // }
    //
    // if (!communicationTime) {
    //     promptInfo("沟通时长不能为空!");
    //     return;
    // }
    //
    // if (followWay == '3') {
    //     if (!wechat) {
    //         promptInfo("微信号不能为空!");
    //         return;
    //     } else if (wechat.length > 50) {
    //         promptInfo("微信号不能大于50个字！");
    //         return;
    //     }
    // }
    //
    // if (!clueScore) {
    //     promptInfo("评分不能为空!");
    //     return;
    // }
    //
    // if (tag.length > 65535) {
    //     promptInfo("标签长度不能大于65535个字符！");
    //     return;
    // }
    //
    // if (!followDetail) {
    //     promptInfo("跟进详情不能为空!");
    //     return;
    // } else if (followDetail.length > 255) {
    //     promptInfo("跟进详情不能大于255个字！");
    //     return;
    // }
    //

    var bootstrapValidator = $(".card-body").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    }
    if (followWay == '1' || followWay == '4') {
        if (!accountUploadId) {
            promptInfo("上传电话账号页不能为空!");
            return;
        }

        if (!minUploadId) {
            promptInfo("上传电话时长页不能为空!");
            return;
        }
    } else if (followWay == '2') {
        //拜访(2)
        attachmentUploadId = $.trim($("#visitScreen").val());
        if (!attachmentUploadId) {
            promptInfo("上传拜访图片不能为空!");
            return;
        }
    } else if (followWay == '6') {
        //陪访(6)
        attachmentUploadId = $.trim($("#visitScreen").val());
        if (!attachmentUploadId) {
            promptInfo("上传陪访图片不能为空!");
            return;
        }
    } else if (followWay == '3') {
        //微信(3)
        attachmentUploadId = $.trim($("#weChatScreen").val());
        if (!attachmentUploadId) {
            promptInfo("上传聊天记录不能为空!");
            return;
        }
    } else if (followWay == '5') {
        //邮箱(5)
        attachmentUploadId = $.trim($("#emailScreen").val());
        if (!attachmentUploadId) {
            promptInfo("上传邮件截图不能为空!");
            return;
        }
    }
    var jsonData = {
        "clueId": clueId,
        "customerId": customerId,
        "cluePoolId": poolId,
        "source": source,
        "followWay": followWay,
        "followTm": followTm,
        "nextPlanTime": nextPlanTime,
        "clueContactId": clueContactId,
        "contactName": contactName,
        "contactInformation": contactInformation,
        "email":email,
        "visitAddress": visitAddress,
        "customerIntention": customerIntention,
        "customerQuality": customerQuality,
        "followPurpose": followPurpose,
        "followValue": followValue,
        "communicationTime": communicationTime,
        "accompanyingPerson": accompanyingPerson,
        "mainVisitor": mainVisitor,
        "wechat": wechat,
        "clueScore": clueScore,
        "tag": tag,
        "followDetail": followDetail,
        //"remark": remark,
        "accountUploadId": accountUploadId,
        "minUploadId": minUploadId,
        "attachmentUploadId": attachmentUploadId,
        "customerType": customerType
    };
    $.ajax({
        url: '/clueFollow/addClueFollow',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == '000000') {
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                var jumpUrl;
                                var title = "查看";
                                if(source == '0'){
                                    var clueId = $("#customerInput").val();
                                    title = "线索详情";
                                    jumpUrl = "/front/cluePoolManager/user/clueDetail?clueId=" + clueId;
                                } else if (source == '1') {
                                    var customerId = $("#customerInput").val();
                                    if(customerType == "0") {
                                        title = "客户详情";
                                        jumpUrl = "/front/user/customerManager/customerDetail?customerId=" + customerId
                                    }else{
                                        getPersonalContactId(customerId,contactName,contactInformation,customerType);
                                        title = "联系人详情";
                                        jumpUrl = "/front/user/contactManager/contactDetail?contactId=" + contactId
                                    }
                                }
                                if (jumpUrl) {
                                    var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                    var navTab = parent.$multitabs._getNavTab($thisTabs);
                                    closeTab(navTab);
                                    openTab(title, jumpUrl);
                                    delStorageAndRemove(navTab);
                                } else {
                                    window.location.reload();
                                }
                            }
                        }
                    }
                });
            } else {
                $.alert("保存失败");
            }
        }),
        error: (function (res) {
            $.alert("保存失败");
        })
    });
}
var contactId = "";
function getPersonalContactId(customerId,contactName,contactInformation,contactNature) {
    $.ajax({
        url: '/contact/getCustomerIdAndContactNameAndAccountId',
        type: 'POST',
        dataType: "json",
        async: false,
        data: {
            customerId: customerId,
            contactName : contactName,
            contactInformation : contactInformation,
            contactNature : contactNature
        },
        success: (function (data) {

            if (data.code == "000000") {
                if (data.data.contactId != null) {
                    contactId = data.data.contactId;
                }
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}



function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

/**
 * 获得客户名称下拉
 */
function getCustomerSelect(){
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/customerController/getCustomerList',
        cache : false,
        data:{
        },
        async : true,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '<option value="">请选择</option>';
                $.each(data.data, function(n, value) {
                    /*html += "<option value=" + value.customerId + ">" +  value.customerName + "</option>";*/
                    html += '<option value=' + value.customerId + ' data-type="' + value.customerType + '">' +  value.customerName + '</option>';
                });

                //$('#customerInput').html(html).selectpicker('refresh');
                $("#customerInput").html(html).selectpicker('refresh').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {      // 内容变更触发
                    var customerType = $('#customerInput option:selected').data('type');
                    $('#name').val("");
                    $('#phone').val("");
                    //if(customerType == '0') {
                        $('#name').attr('disabled', false);
                        $('#phone').attr('disabled', false);
                    //}

                });
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

/*function isPhone(){
    if(!isMobile($('#phone').val())){
        $.alert('请输入正确的手机号码')
        $('#phone').val('')
    }
}*/



function isMobile(inputString) {
    var partten = /^1[34578]\d{9}$/;
    var fl = false;
    if (partten.test(inputString)) {
        return true;
    }
    else {
        return false;
    }
}